package main

import (
	"encoding/csv"
	"fmt"
	"os"
	"strconv"
	"strings"
	"time"

	"gonum.org/v1/plot"
	"gonum.org/v1/plot/plotter"
	"gonum.org/v1/plot/plotutil"
	"gonum.org/v1/plot/vg"
	"gonum.org/v1/plot/vg/draw"
)

func main() {
	// Read delta.dat
	file, err := os.Open("delta.dat")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	reader := csv.NewReader(file)
	reader.Comma = ','
	reader.Comment = '#' // Ignore comment lines (starting with #)

	records, err := reader.ReadAll()
	if err != nil {
		panic(err)
	}

	// Parse data into (date, money) points
	var points plotter.XYs
	for _, record := range records {
		// Skip empty lines or malformed rows
		if len(record) < 2 {
			continue
		}

		// Parse date (mm/dd/yyyy)
		dateStr := strings.TrimSpace(record[0])
		date, err := time.Parse("1/2/2006", dateStr) // Go's reference date format
		if err != nil {
			fmt.Printf("Skipping invalid date: %s (error: %v)\n", dateStr, err)
			continue
		}

		// Parse money value (trim leading/trailing spaces first)
		moneyStr := strings.TrimSpace(record[1])
		money, err := strconv.ParseFloat(moneyStr, 64)
		if err != nil {
			fmt.Printf("Skipping invalid money: %s (error: %v)\n", moneyStr, err)
			continue
		}

		// Convert date to Unix timestamp (for X-axis plotting)
		points = append(points, plotter.XY{
			X: float64(date.Unix()),
			Y: money,
		})
	}

	// Create a new plot
	p := plot.New()

	p.Title.Text = "Graph of Money"
	p.X.Label.Text = "Date"
	p.Y.Label.Text = "Rest Money"

	// Add a line with markers
	line, err := plotter.NewLine(points)
	if err != nil {
		panic(err)
	}
	line.LineStyle.Width = vg.Points(2)
	line.LineStyle.Color = plotutil.Color(0) // Blue color

	// Add markers (use built-in circle marker without glyphs package)
	scatter, err := plotter.NewScatter(points)
	if err != nil {
		panic(err)
	}

	scatter.GlyphStyle.Shape = draw.CircleGlyph{} // Correct circle marker in v0.16.0
	scatter.GlyphStyle.Radius = vg.Points(4)      // Marker size
	scatter.GlyphStyle.Color = plotutil.Color(0)  // Match line color

	p.Add(line, scatter)
	p.Legend.Add("Trace my own money", line, scatter)

	// Format X-axis as dates
	p.X.Tick.Marker = plot.TimeTicks{Format: "Jan 02"}

	// Save plot to PNG file
	if err := p.Save(8*vg.Inch, 5*vg.Inch, "money_plot.png"); err != nil {
		panic(err)
	}

	fmt.Println("Plot saved as money_plot.png")
}
